
using System.ServiceModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using AdventureWorks.Client.Objects;
using AdventureWorks.Client.Silverlight.EmployeeServiceRef;
using Xomega.Framework;

namespace AdventureWorks.Client.Silverlight
{
    public partial class EmployeeDetails : Page
    {
        private EmployeeObject obj;
        private bool isNew = false;

        public EmployeeDetails()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            obj = new EmployeeObject();
            obj.TemporaryKeyProperty.Required = false;
            obj.EmployeeIdProperty.Required = false;
            pnlMain.DataContext = obj;
            gridPayHistory.ItemsSource = obj.PayHistoryList;
            isNew = NavigationContext.QueryString.Count == 0;
            if (!isNew) Load(true);
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            bool? modified = obj.IsModified();
            if (modified.HasValue && modified.Value && MessageBox.Show(
                "You have unsaved changes. Do you want to discard them and navigate away?",
                "Unsaved Changes", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                e.Cancel = true;
        }

        private void Load(bool readKeys)
        {
            if (readKeys)
            {
                obj.TemporaryKeyProperty.SetValue(NavigationContext.QueryString["TemporaryKey"]);
                obj.EmployeeIdProperty.SetValue(NavigationContext.QueryString["EmployeeId"]);
            }
            EmployeeServiceClient svcEmployee = new EmployeeServiceClient();
            svcEmployee.ReadCompleted += delegate(object sender, ReadCompletedEventArgs ce)
            {
                if (ce.Error != null) MessageBox.Show(ErrorList.FromException(
                    ce.Error).ErrorsText, "Service Errors", MessageBoxButton.OK);
                else
                {
                    obj.FromDataContract(ce.Result);
                    isNew = false;
                    btnDelete.IsEnabled = true;
                }
                svcEmployee.CloseAsync();
            };
            EmployeeKey inRead = new EmployeeKey();
            obj.ToDataContract(inRead);
            svcEmployee.ReadAsync(inRead);
            svcEmployee.PayHistory_ReadListCompleted += delegate(object sender, PayHistory_ReadListCompletedEventArgs ce)
            {
                if (ce.Error != null) MessageBox.Show(ErrorList.FromException(
                    ce.Error).ErrorsText, "Service Errors", MessageBoxButton.OK);
                else obj.PayHistoryList.FromDataContract(ce.Result);
            };
            EmployeeKey inPayHistory_ReadList = new EmployeeKey();
            obj.ToDataContract(inPayHistory_ReadList);
            svcEmployee.PayHistory_ReadListAsync(inPayHistory_ReadList);
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            obj.Validate(true);
            ErrorList valErr = obj.GetValidationErrors();
            if (valErr.HasErrors())
            {
                MessageBox.Show(valErr.ErrorsText, "Validation Errors", MessageBoxButton.OK);
                return;
            }

            EmployeeServiceClient svcEmployee = new EmployeeServiceClient();

            if (isNew)
            {
            }
            else
            {
                // for existing objects update the object and reload
                svcEmployee.UpdateCompleted += delegate(object s, AsyncCompletedEventArgs ce)
                {
                    if (ce.Error != null) MessageBox.Show(ErrorList.FromException(
                        ce.Error).ErrorsText, "Service Errors", MessageBoxButton.OK);
                    else
                    {
                        obj.SetModified(false, true);
                        svcEmployee.CloseAsync();
                        Load(false);
                    }
                };
                Employee_UpdateInput inUpdate = new Employee_UpdateInput();
                obj.ToDataContract(inUpdate);
                svcEmployee.UpdateAsync(inUpdate);
            }
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show(
                "Are you sure you want to delete this object?\nThis action cannot be undone.",
                "Delete Confirmation", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel) return;
            if (isNew) Close();

        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void Close()
        {
            NavigationService.GoBack();
        }
    }
}
